import { useRef, useReducer, useState } from 'react';
import type { DependencyList } from 'react';

// 强制刷新
export function useUpdate(): () => void {
	const [, update] = useReducer((num: number): number => num + 1, 0);

	return update;
}

const depsAreSame = (oldDeps: DependencyList, deps: DependencyList): boolean => {
	if (oldDeps === deps) return true;

	for (let i = 0; i < oldDeps.length; i++) {
		if (!Object.is(oldDeps[i], deps[i])) return false;
	}

	return true;
};
// 获取最新值
export const useCreation = <T>(fn: () => T, deps: DependencyList) => {
	const { current } = useRef({
		deps,
		obj: undefined as undefined | T,
		initialized: false
	});

	if (current.initialized === false || !depsAreSame(current.deps, deps)) {
		current.deps = deps;
		current.obj = fn();
		current.initialized = true;
	}

	return current.obj as T;
};

// type Parameters<T extends (args: any) => any> = T extends (args: infer P) => any ? P : never;

type Service<TParams extends any[], TData> = (...args: TParams) => Promise<TData>;

export function useDebounceRequest<TParams extends any[], TData>(fn: Service<TParams, TData>) {
	const requestDone = useRef(true);
	const [loading, setLoading] = useState(false);

	const requestFn = async (...args: TParams) => {
		try {
			if (!requestDone.current) return Promise.reject('上次请求未完成');
			requestDone.current = false;
			setLoading(true);
			return await fn?.(...args).finally(() => {
				requestDone.current = true;
				setLoading(false);
			});
		} catch (error) {
			console.log('=====', error);
		}
	};

	return { loading, requestFn };
}
